#include "../../common/etcder.hpp"
#include "../../common/channel.hpp"

#include "main.pb.h"
#include <gflags/gflags.h>
#include <brpc/server.h>
#include <butil/logging.h>

DEFINE_bool(log_mode, false, "程序的运行模式: true-发布模式 false-调试模式");
DEFINE_string(log_file, "", "发布模式下，制定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，制定日志的输出等级");

DEFINE_string(etcd_host, "127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(service_dir, "/service", "服务监测根目录");
DEFINE_string(service_instance, "/echo/instance", "当前服务实例名称");
DEFINE_string(dest_host, "0.0.0.0:8888", "当前服务实例地址");

DEFINE_int32(listen_port, 8888, "Rpc服务器监听端口");

// 1.创建一个继承于EchoService的接口类
class EchoServiceImpl : public example::EchoService
{
public:
    using ptr = std::shared_ptr<EchoServiceImpl>;
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}
    void Echo(google::protobuf::RpcController *controller,
              const ::example::EchoRequest *request,
              ::example::EchoResponse *response,
              ::google::protobuf::Closure *done)
    {
        // 管理rpc对象
        brpc::ClosureGuard rpc_guard(done);
        // 处理业务
        std::cout << "收到消息# " << request->message() << std::endl;
        std::string resp = request->message() + "--已接收";
        response->set_message(resp);

        // 理论上需要Closure来进行业务响应的发送，但是我们已经管理了这个done对象
        // done->Run();
    }
};

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    initLogger(FLAGS_log_mode, FLAGS_log_file, FLAGS_log_level);

    // 关闭brpc默认日志输出
    {
        logging::LoggingSettings settings;
        settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
        logging::InitLogging(settings);
    }

    // 进行brpc框架服务器的搭建和服务注册
    {
        // 构造服务器
        auto server = std::make_shared<brpc::Server>();
        // 构建服务
        EchoServiceImpl::ptr echo_service = std::make_shared<EchoServiceImpl>();
        // 添加服务
        int ret = server->AddService(echo_service.get(), brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
        if (ret == -1)
        {
            std::cout << "服务器添加服务失败" << std::endl;
            return -1;
        }
        auto options = std::make_shared<brpc::ServerOptions>();
        // 启动服务器
        options->idle_timeout_sec = -1; // 连接空闲超时时间
        options->num_threads = 1;
        ret = server->Start(FLAGS_listen_port, options.get());
        if (ret == -1)
        {
            std::cout << "服务器启动失败" << std::endl;
            return -1;
        }
        // 注册服务
        zhong::etcder::Registry::ptr registrar = std::make_shared<zhong::etcder::Registry>(FLAGS_etcd_host);

        // service_instance需要不同因为etcd框架的键相同时，value会修改
        std::string service_instance = FLAGS_service_dir + FLAGS_service_instance;
        registrar->registry(service_instance, FLAGS_dest_host);

        // 休眠等待服务器结束运行
        server->RunUntilAskedToQuit();
    }
}

